package com.adnaan.admin.service.impl;

import com.adnaan.admin.mapper.SysMenuMapper;
import com.adnaan.admin.model.entity.SysMenu;
import com.adnaan.admin.service.SysMenuService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统菜单服务实现类
 */
@Service
@RequiredArgsConstructor
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    /**
     * 根据用户ID查询菜单列表
     *
     * @param userId 用户ID
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> selectMenusByUserId(Long userId) {
        return baseMapper.selectMenusByUserId(userId);
    }

    /**
     * 获取路由菜单树
     *
     * @param userId 用户ID
     * @return 菜单树
     */
    @Override
    public List<SysMenu> buildMenuTree(Long userId) {
        // 查询菜单列表
        List<SysMenu> menus = selectMenusByUserId(userId);

        // 过滤只显示目录和菜单
        menus = menus.stream()
                .filter(menu -> menu.getMenuType().equals("M") || menu.getMenuType().equals("C"))
                .filter(menu -> menu.getIsVisible() == 0)
                .sorted(Comparator.comparing(SysMenu::getSort))
                .collect(Collectors.toList());

        // 构建树形结构
        return buildMenuTree(menus, 0L);
    }

    /**
     * 根据角色ID查询菜单ID列表
     *
     * @param roleId 角色ID
     * @return 菜单ID列表
     */
    @Override
    public List<Long> selectMenuIdsByRoleId(Long roleId) {
        return baseMapper.selectMenuIdsByRoleId(roleId);
    }

    /**
     * 构建前端选择树
     *
     * @return 菜单树
     */
    @Override
    public List<SysMenu> buildMenuSelectTree() {
        // 查询所有菜单
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysMenu::getStatus, 0)
                .orderByAsc(SysMenu::getSort);
        List<SysMenu> menus = list(queryWrapper);

        // 构建树形结构
        return buildMenuTree(menus, 0L);
    }

    /**
     * 构建菜单树
     *
     * @param menus    菜单列表
     * @param parentId 父级ID
     * @return 菜单树
     */
    private List<SysMenu> buildMenuTree(List<SysMenu> menus, Long parentId) {
        return menus.stream()
                .filter(menu -> menu.getParentId().equals(parentId))
                .map(menu -> {
                    menu.setChildren(buildMenuTree(menus, menu.getId()));
                    return menu;
                })
                .collect(Collectors.toList());
    }
} 